// /* eslint-disable */
// console.log('tax injected');
import { transformDataByOpenWeb } from '../../lib/openWebTransform.js';
import { startZeroReport } from './zeroReport.js';
import DGGS from '../commonModule/DGGS.js';
import { startAsyncTable } from './asyncTable.js';
let baseInfoCache;

$(window).ready(function() {
  if (/\/sb/g.test(window.location.pathname)) {
    let frmMain = document.querySelector('#iframehtm');
    if (frmMain) {
      frmMain.onload = function() {
        let clearMsgWindow = setInterval(function() {
          let frmMainWindow = frmMain.contentWindow.document;
          let msgWindow = $('#msg-window', frmMainWindow);
          let hsqjLayer = $('.layui-layer', frmMainWindow);
          if (msgWindow[0] || hsqjLayer[0]) {
            // 财务报表的 弹窗
            msgWindow.hide();
            $('#maskLevel', frmMainWindow).hide();
            // 汇算清缴的 弹窗
            hsqjLayer.hide();
            $('.layui-layer-shade', frmMainWindow).hide();
            clearInterval(clearMsgWindow);
          }
        }, 100);

        binkClick(frmMain);

        let pathname = window.location.pathname;
        if (/\/nssb\/main/g.test(pathname)) {
          getPeriodAndType('zzs');
        } else if (/\/sbzs\/qysds_a/g.test(pathname)) {
          // 所得税
          getPeriodAndType('sds');
        } else if (/cwbb/g.test(pathname)) {
          getPeriodAndType('balance');
        }
      };
    }
  }
  DGGS.hackReportInputPage();


  window.postMessage(
    {
      event: 'getZeroInfo'
    },
    '*'
  );
  // checkZeroReport();
  // 登录填写账号密码
  if (/\/sso\/login/g.test(window.location.pathname)) {
    window.postMessage(
      {
        event: 'getBaseInfo'
      },
      '*'
    );
  }
});

window.addEventListener(
  'message',
  async function({ data }) {
    console.log(data.event);
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'setSaasData') {
      data = data.data;
      let sheet = data.saasData.sheet;
      if (sheet === 'sds' || sheet === 'zzs') {
        fillInput(data, sheet);
      } else {
        fillInput(await transformDataByOpenWeb(data), sheet);
      }
    }
    if (data.event === 'getNationData') {
      getNationData(data.data.taxType);
    }

    if (data.event === 'getBaseInfo') {
      baseInfoCache = data.data;
      autoInputAccount(baseInfoCache);
    }
    if (data.event === 'getZeroInfoBack') {
      if (data.data.isOpenZeroReport) {
        // console.log(data);
        await startZeroReport(data);
      }
    }
    if (data.event === 'zeroReportEnd') {
      startAsyncTable();
    }
    if (data.event === 'asyncTableDetailRequestEnd') {
      window.postMessage({
        event: 'clearZeroReport'
      },
      '*');
      setTimeout(() => {
        window.sessionStorage.clear();
        window.location.href = 'http://etax.beijing.chinatax.gov.cn/sso/logout?service=http%3A%2F%2Fetax.beijing.chinatax.gov.cn%2Fxxmh';  
      }, 500);
    }
  },
  false
);

/**
 * 获取公司信息
 */
function getNationData(taxType) {
  const iframe = window.frames.frmMain.frames.frmSheet;
  let taxInfo = {
    institution: getGsInstitution(iframe) === 'small' ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '' // 税款所属期止
  };

  if (taxType === 'hsqj' && DGGS.isHsqjSmall()) {
    taxInfo.isHsqjSmall = true;
  }

  window.postMessage(
    {
      event: 'backNationData',
      data: {
        taxInfo: taxInfo
      }
    },
    '*'
  );
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  document.querySelector('#userName').value = companyInfo.nationalTaxAccount || companyInfo.nationalTaxId;
  document.querySelector('#passWord').value = companyInfo.nationalTaxPass;
}

function fillInput({ saasData, baseInfo }, sheet) {
  let sheetType = saasData.sheetType;
  let isCwbb = sheetType === 'cwbb';
  let iframeWindow = window.frames.frmMain.frames.frmSheet; // 填报iframe Window对象 财务报表与汇算清缴一致
  let inputData = saasData.data;
  if (sheet === 'sds') {
    let tableData = inputData.openParams.inputData.data.profit;
    if (baseInfo.companyInfo.institutionCode === '2') {
      inputData = {
        'sbbxxForm.yysrLj': tableData.BNLJJE_1,
        'sbbxxForm.yycbLj': tableData.BNLJJE_2,
        'sbbxxForm.lrzeLj': tableData.BNLJJE_30
      };
    } else {
      inputData = {
        'sbbxxForm.yysrLj': tableData.SQJE_1_1,
        'sbbxxForm.yycbLj': tableData.SQJE_1_2,
        'sbbxxForm.lrzeLj': tableData.SQJE_1_15
      };
    }
  }
  let message = '填报成功 ';
  try {
    message = angularFill(
      inputData,
      iframeWindow,
      message,
      isCwbb,
      sheet,
      saasData
    );
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage(
    {
      event: 'fillInputDone',
      data: {
        message: message
      }
    },
    '*'
  );
}

/**
 * 按照angular方式填充
 * @param inputData 原始数据
 * @param iframeWindow 填报iframe的window
 * @param message 提示信息
 * @param isCwbb 是否为财务报表
 * @param sheet 报表类型
 * @param {lastYearData, isYearReport} // 上年数据 是否为年报
 */
function angularFill(
  inputData,
  iframeWindow,
  message,
  isCwbb,
  sheet,
  { lastYearData, isYearReport }
) {
  let angular = iframeWindow.angular;
  let controllerScope = angular.element('#viewCtrlId').scope();

  if (isYearReport) {
    inputData = DGGS.hackYearReportInput(inputData, lastYearData, sheet);
  }

  for (let key in inputData) {
    let value = Number.parseFloat(inputData[key]).toFixed(2) || '0.00';
    let keyFormObj = key.split('.')[0];
    let formVal = eval('controllerScope.' + keyFormObj);
    let tdVal = formVal ? eval('controllerScope.' + key) : 'undefined';

    if (tdVal !== 'undefined') {
      eval('controllerScope.' + key + '=' + value);
    } else if (isCwbb) {
      message += `${key}字段找不到\n`;
    }
  }

  angular
    .element('#viewCtrlId')
    .scope()
    .$apply();

  DGGS.tiggerDomByInputDataKey(inputData, sheet, isYearReport, iframeWindow);

  return message;
}

let getGsInstitution = function(iframeWindow) {
  let gsInstitution = 'small';
  let text = iframeWindow.document.querySelector('.NewTableHead h1').innerText;
  if (text.trim().search('适用执行企业会计准则') != -1) {
    gsInstitution = 'gener';
  } else if (text.trim().search('适用执行小企业会计准则') != -1) {
    gsInstitution = 'small';
  }
  return gsInstitution;
};

let getPeriodAndType = function(mark = 'balance') {
  let timeObj = getPeriodByUrl(mark);
  sendFilter(mark, timeObj.startTime, timeObj.endTime);
};

function binkClick(frmMain) {
  let divSheetlist = frmMain.contentWindow.document.querySelector(
    '#divSheetlist'
  );
  if (divSheetlist) {
    divSheetlist.addEventListener('click', function(e) {
      // 给左侧菜单栏绑定事件
      e.preventDefault();
      let type = 'balance';
      if (
        e.target
        && $(e.target)
          .text()
          .search('资产负债表') > -1
      ) {
        type = 'balance';
      } else if (
        e.target
        && $(e.target)
          .text()
          .search('现金流量表') > -1
      ) {
        type = 'cash';
      } else if (
        e.target
        && $(e.target)
          .text()
          .search('利润表') > -1
      ) {
        type = 'profit';
      }
      getPeriodAndType(type);
    });
  }
}

function getPeriodByUrl(mark) {
  let obj = url2json(window.location.href);
  let startTime = mark === 'sds' ? obj.skssq_q : obj.skssqQ;
  let endTime = mark === 'sds' ? obj.skssq_z : obj.skssqZ;
  return {
    startTime: startTime ? startTime.slice(0, startTime.length - 3) : '',
    endTime: endTime ? endTime.slice(0, endTime.length - 3) : ''
  };
}

function sendFilter(type, startTime, endTime) {
  window.postMessage(
    {
      event: 'setPeriodAndType',
      data: {
        type: type,
        startTime: startTime,
        endTime: endTime
      }
    },
    '*'
  );
}

function url2json(url) {
  let index = -1,
    str = '',
    arr = [],
    length = 0,
    res = {};
  if (url.indexOf('?') != -1) {
    index = url.indexOf('?');
    str = url.substring(index + 1);
    arr = str.split('&');
    length = arr.length;
    for (let i = 0; i < length - 1; i++) {
      res[arr[i].split('=')[0]] = arr[i].split('=')[1];
    }
  } else {
    res = {};
  }
  return res;
}
